package com.xhs.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.xhs.dto.request.CompanyAddParams;
import com.xhs.dto.request.CompanyEditParams;
import com.xhs.dto.request.CompanyPageParams;
import com.xhs.dto.request.DelCompanyParam;
import com.xhs.entity.MeCompanyEntity;
import com.xhs.exception.CommonException;
import com.xhs.mapper.MeCompanyMapper;
import com.xhs.message.Result;
import com.xhs.message.ReturnResult;
import com.xhs.service.MeCompanyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.mybatisflex.core.query.QueryMethods.noCondition;
import static com.xhs.entity.table.MeBeneficiaryEntityTableDef.ME_BENEFICIARY_ENTITY;
import static com.xhs.entity.table.MeCompanyEntityTableDef.ME_COMPANY_ENTITY;

/**
 * 客户表 服务层实现。
 *
 * @author xhs
 * @since 2023-08-03
 */
@Slf4j
@Service
public class MeCompanyServiceImpl extends ServiceImpl<MeCompanyMapper, MeCompanyEntity> implements MeCompanyService {
    /**
     * 分页查询客户信息
     *
     * @param pageParams 查询条件
     * @return ReturnResult<Object>
     */
    @Override
    public ReturnResult<Object> getCompanyInfoPage(CompanyPageParams pageParams) {
        Page<MeCompanyEntity> page = new Page<>(pageParams.getPageNumber(), pageParams.getPageSize());
        Page<MeCompanyEntity> pageInfo = queryChain()
                .select(ME_COMPANY_ENTITY.DEFAULT_COLUMNS)
                .from(ME_COMPANY_ENTITY)
                .where(StringUtils.hasLength(pageParams.getCompanyName()) ? ME_COMPANY_ENTITY.ME_COMP_NAME.eq(pageParams.getCompanyName()) : noCondition())
                .page(page);
        return ReturnResult.build(Result.QUERY_SUCCESS).setData(pageInfo);
    }

    /**
     * 查询企业的受益人
     *
     * @param pageParams 查询条件
     * @return ReturnResult<Object>
     */
    @Override
    public ReturnResult<Object> getCompanyBeneficiary(CompanyPageParams pageParams) {
        Page<MeCompanyEntity> page = new Page<>(pageParams.getPageNumber(), pageParams.getPageSize());
        Page<MeCompanyEntity> list = queryChain()
                .select(ME_COMPANY_ENTITY.DEFAULT_COLUMNS)
                .from(ME_COMPANY_ENTITY.as("c"))
                .leftJoin(ME_BENEFICIARY_ENTITY).as("b").on(ME_COMPANY_ENTITY.ME_COMP_GUID.eq(ME_BENEFICIARY_ENTITY.ME_COMP_GUID))
                .where(StringUtils.hasLength(pageParams.getCompanyName()) ? ME_COMPANY_ENTITY.ME_COMP_NAME.eq(pageParams.getCompanyName()) : noCondition())
                .page(page);
        return ReturnResult.build(Result.QUERY_SUCCESS).setData(list);
    }

    /**
     * 新增企业
     *
     * @param params 参数
     * @return ReturnResult<Object>
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReturnResult<Object> addCompany(CompanyAddParams params) {
        MeCompanyEntity entity = new MeCompanyEntity();
        BeanUtils.copyProperties(params, entity);
        String companyId = "F" + DateUtil.format(new Date(), "yyyyMMdd") + IdUtil.getSnowflakeNextId();
        entity.setMeCompGuid(companyId);
        getMapper().insert(entity);
        return ReturnResult.build(Result.ADD_SUCCESS).setData(companyId);
    }

    /**
     * 删除企业
     *
     * @param paramList 入参
     * @return ReturnResult<String>
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReturnResult<String> delCompany(List<DelCompanyParam> paramList) {
        List<Integer> idList = paramList.stream().map(DelCompanyParam::getId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(idList)) {
            throw new CommonException("企业ID不能为空");
        }
        boolean remove = removeByIds(idList);
        if (remove) {
            return ReturnResult.build(Result.DEL_SUCCESS);
        }
        return ReturnResult.build(Result.DEL_ERROR);
    }

    /**
     * 修改企业
     *
     * @param param 入参
     * @return ReturnResult<String>
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReturnResult<String> updateCompany(CompanyEditParams param) {
        MeCompanyEntity meCompanyEntity = BeanUtil.copyProperties(param, MeCompanyEntity.class);

        boolean updated = this.updateById(meCompanyEntity);
        if (updated) {
            return ReturnResult.build(Result.UPD_SUCCESS);
        }
        return ReturnResult.build(Result.UPD_ERROR);
    }

    /**
     * 根据企业ID查询企业数据
     *
     * @param guId 入参
     * @return ReturnResult<MeCompanyEntity>
     */
    @Override
    public ReturnResult<MeCompanyEntity> getCompany(String guId) {
        MeCompanyEntity meCompany = queryChain()
                .select(ME_COMPANY_ENTITY.DEFAULT_COLUMNS)
                .from(ME_COMPANY_ENTITY)
                .where(ME_COMPANY_ENTITY.ME_COMP_GUID.eq(guId))
                .one();
        return ReturnResult.success(meCompany);
    }
}
